package com.cweb.admin.model.sys.sys_oss_record.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.aliyun.oss.model.CopyObjectResult;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;
import com.cweb.admin.model.sys.sys_config.service.SysConfigService;
import com.cweb.admin.model.sys.sys_oss_record.entity.SysOssRecord;
import com.cweb.admin.model.sys.sys_oss_record.mapper.SysOssRecordMapper;
import com.cweb.framework.base.serivce.BaseMybatisService;
import com.cweb.framework.pojo.CustomException;
import com.cweb.framework.util.ErrorEnum;
import com.cweb.framework.util.MybatisUtil;
import com.cweb.util.net.SslUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;

/**BaseMybatisModel
 * 系统-oss上传记录 服务实现类
 *
 * @author changfan
 * @since 2019-10-28
 */
@Service
public class SysOssRecordService extends BaseMybatisService<SysOssRecordMapper, SysOssRecord> {
    @Autowired
    private ObjectStorageService objectStorageService;
    @Autowired
    private SysConfigService sysConfigService;

    // 记录类型
    private final static String OSS_RECORD_TYPE_TEMP = "temp";

    /**
     * OSS对象查询并保存(id转对象)
     */
    public void selectAndSetJson(JSONObject json, List<String> keys) throws CustomException {
        if (null == keys || null == json) {
            return;
        }
        // 取得对应的oss对象
        List listParamOss = new ArrayList<>();
        List listKeyIdList = new ArrayList<>();
        for (String key : keys) {
            String keyId = "";
            if (null != key && json.containsKey(key) && null != json.getStr(key)) {
                keyId = json.getStr(key);
                listParamOss.add(keyId);
            }
            listKeyIdList.add(keyId);
        }
        Collection<SysOssRecord> listOssRecord = this.listByIds(listParamOss);
        for (SysOssRecord sysOssRecord : listOssRecord) {
            int index = listKeyIdList.indexOf(sysOssRecord.getId());
            if (index != -1) {
                json.put(keys.get(index), JSONUtil.parseObj(sysOssRecord));
            }
        }
    }

    /**
     * OSS临时文件上传
     */
    public SysOssRecord uploadTempFile(MultipartFile multipartFile) throws CustomException {
        if (null == multipartFile) {
            throw new CustomException(ErrorEnum.COMM_FILE_READ_ERROR);
        }
        try {
            // 创建上传记录
            SysOssRecord sysOssRecord = new SysOssRecord();
            MybatisUtil.initNewObj(sysOssRecord);
            sysOssRecord.setType(OSS_RECORD_TYPE_TEMP);
            sysOssRecord.setBucket(sysConfigService.getConfigStr("OSS_ALIYUN_TEMP_BUCKET"));
            sysOssRecord.setKey(DateUtil.format(new Date(), "yyyyMMdd") + "/" + IdUtil.fastSimpleUUID() + "_" + multipartFile.getOriginalFilename());
            sysOssRecord.setFileName(multipartFile.getOriginalFilename());
            // 上传处理
            PutObjectResult putObjectResult = objectStorageService.upload(sysOssRecord.getBucket(), sysOssRecord.getKey(), multipartFile.getInputStream());
            sysOssRecord.setUrl(objectStorageService.getImgUrl(sysOssRecord.getBucket(), sysOssRecord.getKey()));
            // 保存
            this.save(sysOssRecord);
            log.info("OSS临时文件上传【{}】", sysOssRecord.getKey());
            return sysOssRecord;
        } catch (IOException e) {
            throw new CustomException(ErrorEnum.COMM_FILE_READ_ERROR);
        }
    }

    /**
     * OSS录音文件上传
     */
    public SysOssRecord uploadRecordFile(String type, String newBucket, String paramUrl, String fileName) throws CustomException {
        if (null == paramUrl) {
            throw new CustomException(ErrorEnum.COMM_FILE_READ_ERROR);
        }
        try {
            URL url = new URL(paramUrl);
            SslUtil.ignoreSsl(); // 忽略ssh证书
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//        // 设置超时间为3秒
//        conn.setConnectTimeout(3*1000);
            // 防止屏蔽程序抓取而返回403错误
            conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
            // 得到输入流
            InputStream inputStream = conn.getInputStream();
            // 创建上传记录
            SysOssRecord sysOssRecord = new SysOssRecord();
            MybatisUtil.initNewObj(sysOssRecord);
            sysOssRecord.setType(type);
            sysOssRecord.setBucket(newBucket);
            sysOssRecord.setKey(type + "/" + DateUtil.format(new Date(), "yyyyMMdd") + "/" + IdUtil.fastSimpleUUID() + "_" + fileName);
            sysOssRecord.setFileName(fileName);
            // 上传处理
            ObjectMetadata objectMetadata = new ObjectMetadata();
            objectMetadata.setContentDisposition("attachment;filename=\"" + fileName + "\""); // 强制下载
            PutObjectResult putObjectResult = objectStorageService.upload(sysOssRecord.getBucket(), sysOssRecord.getKey(), inputStream, objectMetadata);
            sysOssRecord.setUrl(objectStorageService.getImgUrl(sysOssRecord.getBucket(), sysOssRecord.getKey()));
            // 保存
            this.save(sysOssRecord);
            log.info("OSS录音文件上传【{}】", sysOssRecord.getKey());
            return sysOssRecord;
        } catch (Exception e) {
            log.error(e);
            throw new CustomException(ErrorEnum.COMM_FILE_READ_ERROR);
        }
    }

    static TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }
    }};


    /**
     * OSS文件复制
     */
    public SysOssRecord copyFile(String type, String oldId, String newBucket) throws CustomException {
        if (null == oldId) {
            return new SysOssRecord();
        }
        SysOssRecord oldOssFile = this.getById(oldId);
        if (null == oldOssFile) {
            throw new CustomException(ErrorEnum.COMM_OBJ_NO_FIND);
        }
        if (!OSS_RECORD_TYPE_TEMP.equals(oldOssFile.getType())) {
            // 非临时目录的记录，不进行复制
            return oldOssFile;
        }

        // 创建上传记录
        SysOssRecord sysOssRecord = new SysOssRecord();
        MybatisUtil.initNewObj(sysOssRecord);
        sysOssRecord.setType(type);
        sysOssRecord.setBucket(newBucket);
        sysOssRecord.setKey(type + "/" + DateUtil.format(new Date(), "yyyyMMdd") + "/" + IdUtil.fastSimpleUUID() + "_" + oldOssFile.getFileName());
        sysOssRecord.setFileName(oldOssFile.getFileName());
        // 复制
        CopyObjectResult copyObjectResult = objectStorageService.copyFile(oldOssFile.getBucket(), oldOssFile.getKey(), sysOssRecord.getBucket(), sysOssRecord.getKey());
        sysOssRecord.setUrl(objectStorageService.getImgUrl(sysOssRecord.getBucket(), sysOssRecord.getKey()));
        // 保存
        this.save(sysOssRecord);
        log.info("OSS文件复制【{}】", sysOssRecord.getKey());
        return sysOssRecord;
    }
}
